package com.tuanzi.loan.business.repository.user.impl;

import com.tuanzi.loan.business.entity.user.LoanUserAgreement;
import com.tuanzi.loan.business.repository.user.custom.LoanUserAgreementCustomRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.user.LoanUserAgreementSearchRequest;
import com.tuanzi.loan.vo.response.user.LoanUserAgreementResponse;
import org.apache.commons.collections.CollectionUtils;
import org.jooq.Record;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanUserAgreement.LOAN_USER_AGREEMENT;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanUserAgreementOnlineProduct.LOAN_USER_AGREEMENT_ONLINE_PRODUCT;

/**
 * @Author: chenweijun
 * @Date: 2019/9/25 10:51
 */
@Repository
public class LoanUserAgreementRepositoryImpl extends JOOQBaseRepositoryPlus implements LoanUserAgreementCustomRepository{

    @Override
    public Page<LoanUserAgreementResponse> list(LoanUserAgreementSearchRequest searchRequest, Pageable pageable) {

        fields(LOAN_USER_AGREEMENT.fields());
        leftJoin(LOAN_USER_AGREEMENT_ONLINE_PRODUCT, LOAN_USER_AGREEMENT.RULE_ID.eq(LOAN_USER_AGREEMENT_ONLINE_PRODUCT.RULE_ID));
        eq(LOAN_USER_AGREEMENT.STATUS, searchRequest.getStatus());
        in(LOAN_USER_AGREEMENT_ONLINE_PRODUCT.PARENT_PRODUCT_ID, searchRequest.getParentProductId());
        ge(LOAN_USER_AGREEMENT.CREATE_DATE, searchRequest.getStartDate());
        le(LOAN_USER_AGREEMENT.CREATE_DATE, searchRequest.getEndDate());
        groupBy(LOAN_USER_AGREEMENT.RULE_ID);

        return search(pageable, record -> {
            LoanUserAgreementResponse response = new LoanUserAgreementResponse();
            response.setId(record.get(LOAN_USER_AGREEMENT.ID));
            response.setStatus(record.get(LOAN_USER_AGREEMENT.STATUS));
            response.setRuleId(record.get(LOAN_USER_AGREEMENT.RULE_ID));
            response.setCreateDate(record.get(LOAN_USER_AGREEMENT.CREATE_DATE));
            return response;
        });
    }

    @Override
    public LoanUserAgreement findTopOne() {
        Record record =  dslContext.select(LOAN_USER_AGREEMENT.fields()).from(LOAN_USER_AGREEMENT).orderBy(LOAN_USER_AGREEMENT.RULE_ID.desc()).limit(1).fetchOne();
        return record == null ? null : record.into(LoanUserAgreement.class);
    }

    @Override
    protected TableImpl getTable() {
        return LOAN_USER_AGREEMENT;
    }
}
